package cn.jjxx.modules.sys.controller;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;

import cn.jjxx.core.common.controller.BaseTreeController;
import cn.jjxx.core.common.entity.tree.TreeSortUtil;
import cn.jjxx.core.model.PageJson;
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.QueryPropertyPreFilter;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresPathPermission;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.modules.sys.entity.Dict;
import cn.jjxx.modules.sys.entity.Menu;
import cn.jjxx.modules.sys.entity.Role;
import cn.jjxx.modules.sys.service.IDictService;
import cn.jjxx.modules.sys.service.IMenuService;

@Controller
@RequestMapping("${admin.url.prefix}/sys/menu")
@RequiresPathPermission("sys:menu")
public class MenuController extends BaseTreeController<Menu, String> {
	
	@Autowired
	protected IMenuService menuService;
	@Autowired
	protected IDictService dictService;
	
	private static final String CONTRL_TYPE = "contrlType";//控制类型

	/**
	 * @Description: 跳转至创建菜单界面 .<br>
	 * @param role 角色.<br>
	 * @param model 模型.<br>
	 * @author 郑成功 .<br>
	 * @date 2018-11-8 下午2:03:12.<br>
	 */
	@RequestMapping(value = "createMenu", method = RequestMethod.GET)
	public String createMenu(Role role, Model model, HttpServletRequest request, HttpServletResponse response) {
		String menuId = request.getParameter("menuId");
		Menu menu = new Menu();
		if(!ObjectUtils.isNullOrEmpty(menu)){
			Menu parent = menuService.selectById(menuId);
			if(!ObjectUtils.isNullOrEmpty(parent)){
				menu.setParent(parent);
				menu.setParentId(parent.getId());
			}
		}
		model.addAttribute("data", menu);
		return display("edit");
	}
	
	@RequestMapping(value = "{id}/updateMenu", method = RequestMethod.GET)
	public String _showUpdate(@PathVariable("id") String id, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		Menu menu = get(id);
		if(StringUtils.isNotEmpty(menu.getType())){
			List<String> list = ObjectUtils.isNullOrEmpty(menu.getType())?new ArrayList<String>():Arrays.asList(menu.getType().split(","));
			List<String> ctrlList = ObjectUtils.isNullOrEmpty(menu.getCtrlType())?new ArrayList<String>():Arrays.asList(menu.getCtrlType().split(","));
			model.addAttribute("typeIds", list);
			model.addAttribute("ctrlTypeIds", ctrlList);
		}
		model.addAttribute("data", menu);
		return display("edit");
	}
	
	
	/**
	 * 根据页码和每页记录数，以及查询条件动态加载数据
	 * @param type 根据组织类型选择0表示管理单元 1表示组织单元
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "menuTreeData")
	public void treeData(Queryable queryable,
			@RequestParam(value = "nodeid", required = false, defaultValue = "") String nodeid,
			@RequestParam(value = "async", required = false, defaultValue = "false") boolean async,
			@RequestParam(value = "type", required = false) String type,
			@RequestParam(value = "isContain", required = false, defaultValue = "false") boolean isContain,
			@RequestParam(value = "id", required = false) String id,
			HttpServletRequest request, HttpServletResponse response,Menu menu) throws IOException {
		EntityWrapper<Menu> entityWrapper = new EntityWrapper<Menu>(Menu.class);
		entityWrapper.setTableAlias("t.");
		List<Menu> treeNodeList = null;
		Field[] fields = entityClass.getDeclaredFields();  
		for(Field f:fields){
			if(f.getName().equals("code")){
				entityWrapper.orderBy("code");
			}
		}
		if(StringUtils.isNotEmpty(type)){
			queryable.addCondition("type", type);
		}
		if(isContain&&StringUtils.isNotEmpty(id)){
			entityWrapper.notIn("id", id);
		}
		if(!ObjectUtils.isNullOrEmpty(menu.getIsfunc())){
			entityWrapper.eq("isfunc", menu.getIsfunc());
		}
		if(!ObjectUtils.isNullOrEmpty(menu.getIsshow())){
			entityWrapper.eq("isshow", menu.getIsshow());
		}
		if (!async) { // 非异步 查自己和子子孙孙
			treeNodeList = menuService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sort(treeNodeList).async(treeNodeList);
		} else { // 异步模式只查自己
			// queryable.addCondition("parentId", nodeid);
			if (ObjectUtils.isNullOrEmpty(nodeid)) {
				// 判断的应该是多个OR条件
				entityWrapper.isNull("parentId");
			} else {
				entityWrapper.eq("parentId", nodeid);
			}
			treeNodeList = menuService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sync(treeNodeList);
		}
		PropertyPreFilterable propertyPreFilterable = new QueryPropertyPreFilter();
		propertyPreFilterable.addQueryProperty("id", "name", "expanded", "hasChildren", "leaf", "loaded", "level",
				"parentId");
		SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
		PageJson<Menu> pagejson = new PageJson<Menu>(treeNodeList);
		String content = JSON.toJSONString(pagejson, filter);
		StringUtils.printJson(response, content);
	}
	
	/**
	 * @Description: 获取菜单的控制类型集合 .<br>
	 * @param menuId 菜单Id.<br>
	 * @author 郑成功 .<br>
	 * @date 2019-3-7 下午3:15:46.<br>
	 */
	@ResponseBody
	@RequestMapping(value = "getMenuContrType" ,method = RequestMethod.POST)
	public Map<String,Object> getMenuContrType(String menuId){
		Map<String,Object> map = new LinkedHashMap<String, Object>();
		Menu menu = menuService.selectById(menuId);
		List<Dict> dicts = dictService.selectDictByGroup(CONTRL_TYPE);
		if(!ObjectUtils.isNullOrEmpty(menu)&&StringUtils.isNotEmpty(menu.getType())){
			List<String> types = Arrays.asList(menu.getCtrlType().split(","));
			List<String> typeNames = new ArrayList<String>();
			for(String type:types){
				for(Dict dict:dicts){
					if(dict.getValue().equals(type)){
						typeNames.add(dict.getLabel());
						break;
					}
				}
			}
			map.put("types", types);
			map.put("typeNames", typeNames);
		}
		return map;
	}
}
